package com.oscar.ehome.utils.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oscar.ehome.R;
import com.oscar.ehome.bean.pagebean.ApplationsBean;
import com.oscar.ehome.bean.pagebean.PageAppBean;
import com.oscar.ehome.bean.pagebean.StudyListBean;
import com.oscar.ehome.provider.gildeimage.GildeUtils;
import com.oscar.ehome.utils.system.SystemConfigFactory;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class CommonUtils {

    //身份证文件 或者 二维码文件
    public static File idcard_file = null;
    //是否是聚焦成功  1代表聚焦成功
    public static int idcard = 0;
    //是否是身份证扫描  1代表是身份证，2代表是二维码
    public static int isIdcard = 0;
    //扫描时截取的帧图片
    public static Bitmap bitmap;
    //是否是第一次进入程序
    public static boolean isFirst = true;
    public static boolean isIndex = true;
    //是否更新
    public static int checkupdate = 0;
    //是否可以长按
    public static int isPress = 0;
    //video是否在下载
    public static int isVideo = 0;
    //pdf是否在下载
    public static int isPdf = 0;
    //frec是否在下载
    public static int isFrec = 0;
    //记录所有activity
    public static List<Activity> activitymap = new ArrayList<>();

    public static Map<String, Object> dakaMap = new HashMap<String, Object>();


    public static String readFlags = "";//已读或者未读  文字版
    public static String readFlag = "";//已读或者未读
    public static String types = "";//类型
    public static String type = "";//类型   文字版

    private static final String SEP1 = ",";
    private static final String SEP2 = "、";

    public static int pop = 1;//是否是筛选消息
    public static int pay = 1;//是否支付

    public static String versioncode = "";//版本号

    public static int url_code = 0;//是否是其他地址

    public static String notifation = "com.oscar.ehome.NotifationReceiver";//广播

    public static int vipVideo = 0;


    public static Context context = null;

    /**
     * 判断网络连接是否已开true 已打开 false 未打开
     */
    public static boolean isNetConn(Context context) {
        boolean bisConnFlag = false;
        ConnectivityManager conManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = conManager.getActiveNetworkInfo();
        if (network != null) {
            bisConnFlag = conManager.getActiveNetworkInfo().isAvailable();
        }
        return bisConnFlag;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static final boolean gPSIsOPen(final Context context) {
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        if (gps) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 返回SD卡的根路径，如果没有路径返回 ""
     *
     * @return
     */
    public static String getSDCardRootPath() {
        String path = "";
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            path = Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            path = "";
        }

        return path;
    }

    /**
     * 返回SD卡的根路径，隐藏不可见的路径
     *
     * @return
     */
    public static String getSDCardRootPath(Context context) {
        String path = context.getCacheDir().getAbsolutePath();
        return path;
    }

    /**
     * 判断程序是否在前台运行
     *
     * @param context
     * @return
     */
    public static boolean isTopActivity(Context context) {
        String packageName = context.getApplicationContext().getPackageName();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            // 应用程序位于堆栈的顶层
            if (packageName.equals(tasksInfo.get(0).topActivity
                    .getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取版本号
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String version = "1.0";
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = context.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo;
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            version = packInfo.versionName;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 获取手机唯一标识
     *
     * @param context
     * @return
     */
    public static String getImei(Context context) {
        String imei = "";
        try {
            TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (telManager.getDeviceId() == null) {
                imei = "";
            } else {
                imei = telManager.getDeviceId();
            }
        } catch (NoSuchFieldError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            imei = "";
        }

        return imei;
    }

    /**
     * 网络提示
     *
     * @param activity
     */
    public static void dialog(final Activity activity) {
        Builder builder = new Builder(activity);
        builder.setMessage("网络未连接!请开启GPRS或WIFI网络连接");

        builder.setTitle("网络提示");

        builder.setPositiveButton("取消", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });

        builder.setNegativeButton("设置", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Build.VERSION.SDK_INT > 10) {

                    activity.startActivityForResult(
                            new Intent(
                                    android.provider.Settings.ACTION_WIRELESS_SETTINGS),
                            55);
                } else {
                    Intent intent = new Intent();
                    ComponentName component = new ComponentName(
                            "com.android.settings",
                            "com.android.settings.WirelessSettings");
                    intent.setComponent(component);
                    intent.setAction("android.intent.action.VIEW");
                    activity.startActivityForResult(intent, 55);
                }
            }
        });

        builder.create().show();
    }

    /**
     * dp转px
     *
     * @param context
     * @param dp
     * @return
     */
    public static int dp2px(Context context, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                context.getResources().getDisplayMetrics());
    }

    /**
     * dip转px
     */
    public static int dipToPx(Context context, float dip) {
        return (int) (dip * context.getResources().getDisplayMetrics().density + 0.5f);
    }

    /**
     * 统一处理返回状态
     */
    public static void status(Activity act, int status_code) {
        if (status_code == 400) {//服务器不理解请求的语法。
        }
        if (status_code == 401) {// 请求要求进行身份验证。
        }
        if (status_code == 403) {// 服务器拒绝请求。

        }
        if (status_code == 404) {// 服务器找不到请求的接口
        }
        if (status_code == 900) {//其他扩展错误描述
        }
        if (status_code == 901) {//操作失败
        }
        if (status_code == 902) {//系统错误
        }
        if (status_code == 903) {//没有权限
        }

    }

    /**
     * 获取listview高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);

    }

    /*
     * 将时间戳转换为时间
	 */
    public static String stampToDate(String s) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String sdate = s + "000";

        String sd = sdf.format(new Date(Long.parseLong(sdate)));

        return sd;
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public static void backgroundAlpha(float bgAlpha, Activity con) {
        WindowManager.LayoutParams lp = con.getWindow().getAttributes();
        lp.alpha = bgAlpha; // 0.0-1.0
        con.getWindow().setAttributes(lp);
    }

    /**
     * 判断是否全是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            int chr = str.charAt(i);
            if (chr < 48 || chr > 57)
                return false;
        }
        return true;
    }

    /***
     * 隐藏键盘
     */
    public static void hide(Activity act) {
        // 判断隐藏软键盘是否弹出
        if (act.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) {
            // 隐藏软键盘
            act.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        }

    }

    /**
     * 强制隐藏输入法键盘
     */
    public static void hideInput(Context context, View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 获取日期时间 String 类型
     *
     * @return
     */
    public static String getDate() {
        Calendar c = Calendar.getInstance();
        String year = String.valueOf(c.get(Calendar.YEAR));
        String month = String.valueOf(c.get(Calendar.MONTH) + 1);
        String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
        String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
        String mins = String.valueOf(c.get(Calendar.MINUTE));
        String sec = String.valueOf(c.get(Calendar.SECOND));
        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins + ":" + sec);
        return sbBuffer.toString();
    }

    /**
     * 状态栏无背景
     *
     * @param on
     */
    public static void setTranslucentStatus(boolean on, Activity act) {
        Window win = act.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        TMSystemBarTintManager tintManager = new TMSystemBarTintManager(act);
        tintManager.setStatusBarTintEnabled(on);
        tintManager.setStatusBarTintResourceNew(0);//状态栏无背景
    }

    /**
     * 设置系统标题背景颜色
     *
     * @param act
     */
    public static void setBaseBackground(Activity act, boolean flag) {
        //说明：XML定义方法接受6位和8位两种表示法，而且开头必须是#，8位定义时前两位表示透明。  4、直接定义色值，如：  int color = 0xff00ff00;
        //这种方法必须使用0x开头，而不是用我们常用的#。与方法3不一样，值也必须用8位表示 ，
        //不接受6位的颜色表示。分组一下0x|ff|ff00ff，0x是代表颜色整数的标记，ff是表示透明度，ff00ff表示RGB颜色值。
        //在安卓的布局xml中写颜色可写成：android:textColor="#19e64dff"
        //在代码设置时使用：paint.setColor(0x19e64dff)    #99CD2D
//        mLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));//使用colors.xml文件中的颜色
//        mTvColorInt.setBackgroundColor(new Integer(-12590395));//使用颜色的int类型值
//        mTvColorHex.setBackgroundColor(Color.parseColor("#3FE2C5"));//使用颜色的16进制类型值
        SystemBarTintManager tintManager = null;
        String color = SystemConfigFactory.getInstance(act).getSystemConfig().getColor();
//        String color = "#00a0e9";
        if (color.equals("") || color == null) {
            color = "#00a0e9";
        } else {
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            CommonUtils.setTranslucentStatus(flag, act);
            tintManager = new SystemBarTintManager(act);
            tintManager.setStatusBarTintEnabled(flag);
            if (flag) {
                tintManager.setStatusBarTintColor(Color.parseColor(color));
            } else {
                tintManager.setStatusBarTintResource(R.color.white);
            }
        }
    }

    /**
     * 解析bean 类型json
     *
     * @param json
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<PageAppBean> fromJson2Array(String json) throws Exception {
        Type type = new TypeToken<List<PageAppBean>>() {
        }.getType();
        List<PageAppBean> list = new Gson().fromJson(json, type);
        return list;
    }


    public static <T> ArrayList<StudyListBean> fromJsonArray(String json) throws Exception {
        Type type = new TypeToken<ArrayList<StudyListBean>>() {
        }.getType();
        ArrayList<StudyListBean> list = new Gson().fromJson(json, type);
        return list;
    }

    /**
     * List转换String
     *
     * @param list :需要转换的List
     * @return String转换后的字符串
     */
    public static String ListToString(List<?> list, int type) {
        StringBuffer sb = new StringBuffer();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) == null || list.get(i) == "") {
                    continue;
                }
                if (type == 1) {
                    // 如果值是list类型则调用自己
                    if (list.get(i) instanceof List) {
//                    sb.append(ListToString(list.get(i)));
//                    sb.append(SEP1);
                    } else if (list.get(i) instanceof Map) {
                        sb.append(MapToString((Map<?, ?>) list.get(i)));
                        sb.append(SEP1);
                    } else {
                        sb.append(list.get(i));
                        sb.append(SEP1);
                    }
                } else {
                    if (list.get(i) instanceof List) {
//                    sb.append(ListToString(list.get(i)));
//                    sb.append(SEP1);
                    } else if (list.get(i) instanceof Map) {
                        sb.append(MapToString((Map<?, ?>) list.get(i)));
                        sb.append(SEP2);
                    } else {
                        sb.append(list.get(i));
                        sb.append(SEP2);
                    }
                }
            }
        }
        return sb.toString();
    }

    /**
     * Map转换String
     *
     * @param map :需要转换的Map
     * @return String转换后的字符串
     */
    public static String MapToString(Map<?, ?> map) {
        StringBuffer sb = new StringBuffer();
        // 遍历map
        for (Object obj : map.keySet()) {
            if (obj == null) {
                continue;
            }
            Object key = obj;
            Object value = map.get(key);
            if (value instanceof List<?>) {
//                sb.append(key.toString() + SEP1 + ListToString((List<?>) value));
                sb.append(SEP1);
            } else if (value instanceof Map<?, ?>) {
                sb.append(key.toString() + SEP1
                        + MapToString((Map<?, ?>) value));
                sb.append(SEP1);
            } else {
                sb.append(key.toString() + SEP1 + value.toString());
                sb.append(SEP1);
            }
        }
        return "M" + sb.toString();
    }

    /**
     * String转换Map
     *
     * @param mapText :需要转换的字符串
     *                :字符串中的分隔符每一个key与value中的分割
     *                :字符串中每个元素的分割
     * @return Map<?,?>
     */
    public static Map<String, Object> StringToMap(String mapText) {

        if (mapText == null || mapText.equals("")) {
            return null;
        }
        mapText = mapText.substring(1);

        mapText = mapText;

        Map<String, Object> map = new HashMap<String, Object>();
        String[] text = mapText.split("\\" + SEP1); // 转换为数组
        for (String str : text) {
            String[] keyText = str.split(SEP1); // 转换key与value的数组
            if (keyText.length < 1) {
                continue;
            }
            String key = keyText[0]; // key
            String value = keyText[1]; // value
            if (value.charAt(0) == 'M') {
                Map<?, ?> map1 = StringToMap(value);
                map.put(key, map1);
            } else if (value.charAt(0) == 'L') {
                List<?> list = StringToList(value);
                map.put(key, list);
            } else {
                map.put(key, value);
            }
        }
        return map;
    }

    /**
     * String转换List
     *
     * @param listText :需要转换的文本
     * @return List<?>
     */
    public static List<Object> StringToList(String listText) {
        if (listText == null || listText.equals("")) {
            return null;
        }
        listText = listText.substring(1);
        List<Object> list = new ArrayList<Object>();
        String[] text = listText.split(SEP1);
        for (String str : text) {
            if (str.charAt(0) == 'M') {
                Map<?, ?> map = StringToMap(str);
                list.add(map);
            } else if (str.charAt(0) == 'L') {
                List<?> lists = StringToList(str);
                list.add(lists);
            } else {
                list.add(str);
            }
        }

        /*********************利用java自身类***********************/
//        String abc = "aaa,bbb,ccc";
//        String[] arr = abc.split(",");
//        List<String> list = java.util.Arrays.aslist(abc);

        return list;
    }

    public static List<String> stringToList(String strs) {
        String str[] = strs.split(",");
        return Arrays.asList(str);
    }


    /**
     * 查询内存是否有数据
     *
     * @param fileAbsolutePath
     * @return
     */
    public static boolean GetVideoFileName(String fileAbsolutePath) {

        File dstDiretory = new File(fileAbsolutePath);
        if (dstDiretory.exists()) {// 目标目录存在
            return true;
        }
        return false;
    }

    public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
    public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
    public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
    public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值

    /**
     * 获取文件指定文件的指定单位的大小
     *
     * @param filePath 文件路径
     * @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
     * @return double值的大小
     */
    public static String getFileOrFilesSize(String filePath, int sizeType) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            blockSize = getFileSize(file);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取文件大小", "获取失败!");
        }
        return FormetFileSize(blockSize);
    }

    private static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    private static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS
     * @param sizeType
     * @return
     */
    private static double FormetFileSize(long fileS, int sizeType) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        switch (sizeType) {
            case SIZETYPE_B:
                fileSizeLong = Double.valueOf(df.format((double) fileS));
                break;
            case SIZETYPE_KB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
                break;
            case SIZETYPE_MB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
                break;
            case SIZETYPE_GB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }

    public static boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    public static String formatTime(String pattern, long milli) {
        int m = (int) (milli / DateUtils.MINUTE_IN_MILLIS);
        int s = (int) ((milli / DateUtils.SECOND_IN_MILLIS) % 60);
        String mm = String.format(Locale.getDefault(), "%02d", m);
        String ss = String.format(Locale.getDefault(), "%02d", s);
        return pattern.replace("mm", mm).replace("ss", ss);
    }

    public static String getUrl(String url, Map<String, String> params) {
        // 添加url参数
        if (params != null) {
            Iterator<String> it = params.keySet().iterator();
            StringBuffer sb = null;
            while (it.hasNext()) {
                String key = it.next();
                String value = params.get(key);
                if (sb == null) {
                    sb = new StringBuffer();
                    sb.append("?");
                } else {
                    sb.append("&");
                }
                sb.append(key);
                sb.append("=");
                sb.append(value);
            }
            url += sb.toString();
        }
        return url;
    }

}
